<!--
  撰写报告
  @author YangMiao 1939724848@qq.com
  @date 2022/04/02 11:13
  @version 1.0.0
-->
<template>
  <div class="list-table noPad">
    <el-form v-if="false" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('基金名称')">
        <el-select v-model="queryParams.fundId" filterable clearable placeholder="请选择基金名称">
          <el-option
            v-for="fundInfo in fundList"
            :key="fundInfo.id"
            :label="fundInfo.fundName"
            :value="fundInfo.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('查询范围')">
        <DatePicker
          v-model="queryParams.queryRangeArr"
          type="daterange"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-if="false" type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{
          $t("搜索")
        }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" tooltip-effect="darkTable" :data="dataList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50" />
      <el-table-column :label="$t('文件名')" prop="fileName" min-width="30%" show-tooltip-when-overflow />
      <el-table-column
        :label="$t('操作')"
        align="center"
        min-width="15%"
        class-name="small-padding fixed-width"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['deal:writingReports:export']"
            size="small"
            type="text"
            icon="el-icon-download"
            @click="clickGeneration(scope.row)"
          >{{ $t('生成报告') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  生成弹窗  -->
    <el-row>
      <mieElFormLayer
        :show-layer="operateData.showLayer"
        :layer-title="operateData.layerTitle"
        :layer-operateform="operateData.layerOperateForm"
        :layer-operate-rules="operateData.layerOperateRules"
        @rightTopBtnClose="rightTopBtnClose"
        @clickLayerOperateCloseBtn="rightTopBtnClose"
        @clickLayerOperateSubmit="clickLayerOperateSubmit"
        @closed="closed"
      >
        <el-row slot="form-content">
          <el-form-item
            v-if="operateData.clickDataSave.type === 'onePage'
              || operateData.clickDataSave.type === 'xmzb'
              || operateData.clickDataSave.type === 'jdthmb'
              || operateData.clickDataSave.type === 'ndthmb'"
            :label="$t('项目名称')"
          >
            <MainBodySelect
              v-model="operateData.layerOperateForm.dealId"
              parameters="deal"
            />
          </el-form-item>
          <el-form-item v-if="operateData.clickDataSave.type === 'onePage'" :label="$t('更新时间')">
            <DatePicker
              v-model="operateData.layerOperateForm.updateTime"
              :placeholder="$t('更新时间')"
            />
          </el-form-item>
          <el-form-item v-if="operateData.clickDataSave.type === ('jjyybg')" :label="$t('基金名称')">
            <el-select
              v-model="operateData.layerOperateForm.fundId"
              filterable
              clearable
              placeholder="请选择基金名称"
            >
              <el-option
                v-for="fundInfo in selectData.fundList"
                :key="fundInfo.id"
                :label="fundInfo.fundName"
                :value="fundInfo.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="operateData.clickDataSave.type === ('jjyybg')" :label="$t('报告类型')">
            <dict-select
              v-model="operateData.layerOperateForm.reportType"
              dictionary="type"
            />
          </el-form-item>
          <el-form-item
            v-if="operateData.clickDataSave.type === ('jjyybg')||
              operateData.clickDataSave.type === 'jdthmb'
              || operateData.clickDataSave.type === 'ndthmb'"
            :label="$t('年份')"
          >
            <el-select v-model="operateData.layerOperateForm.year" placeholder="年份" filterable clearable>
              <el-option
                v-for="item in filterOptionArr"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="(operateData.clickDataSave.type === 'jjyybg' && operateData.layerOperateForm.reportType === 'jb')|| operateData.clickDataSave.type === 'jdthmb'" :label="$t('季度')">
            <el-select v-model="operateData.layerOperateForm.quarter" placeholder="季度" filterable clearable>
              <el-option
                v-for="item in quarterArr"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-row>
      </mieElFormLayer>
    </el-row>
  </div>
</template>

<script>
import { findFund } from '@/api/fund/fundBase'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import mieElFormLayer from '@/views/saas/yueyin/mie/layer/MIE-EL-FormLayer'
import MainBodySelect from '@/components/MainBodySelect/index'

export default {
  name: 'WritingReports',
  components: {
    mieElFormLayer,
    MainBodySelect
  },
  data() {
    return {
      operateType: '',
      loading: false,
      queryParams: {
        fundId: '',
        queryRangeArr: [],
        beginTime: undefined,
        endTime: undefined,
        lps: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()])
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date()
            const start = new Date(new Date().getFullYear(), 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 6)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      operateData: {
        showLayer: false,
        layerTitle: '',
        clickDataSave: {},
        judgeField: {},
        layerOperateForm: {
          dealId: '',
          updateTime: '',
          year: '',
          quarter: ''
        },
        ConfirmationParams: {
          fundId: '',
          fundIssuanceRound: undefined,
          lpId: ''
        },
        layerOperateRules: {}
      },
      selectData: {
        fundList: []
      },
      lpList: [],
      fundIssuanceRoundList: [],
      dataList: [
        {
          fileName: 'onePage',
          type: 'onePage',
          url: '/yueyin/deal/writingReports/exportOnePage',
          fileNameSuffix: 'onePage'
        },
        {
          fileName: '项目周报',
          type: 'xmzb',
          url: '/yueyin/deal/writingReports/exportProjectWeekly',
          fileNameSuffix: '项目周报'
        },
        {
          fileName: '基金运营报告',
          type: 'jjyybg',
          url: '/yueyin/deal/writingReports/exportFundOperationReport',
          fileNameSuffix: '基金运营报告'
        },
        {
          fileName: '季度投后模板',
          type: 'jdthmb',
          url: '/yueyin/deal/writingReports/exportFundConfirmation',
          fileNameSuffix: '季度投后模板'
        },
        {
          fileName: '年度投后模板',
          type: 'ndthmb',
          url: '/yueyin/deal/writingReports/exportFundConfirmation',
          fileNameSuffix: '年度投后模板'
        }
      ],
      filterOptionArr: [],
      quarterArr: ['1', '2', '3', '4']
    }
  },
  mounted() {
  },
  created() {
    const startYear = new Date()
    const startY = 2015
    const endY = startYear.getFullYear() + 20
    for (let i = startY; i < endY; i++) {
      this.filterOptionArr.push(i)
    }
  },
  methods: {
    findIssuanceRoundListByFundId(val) {
      this.operateData.layerOperateForm.lps = ''
      this.operateData.layerOperateForm.fundIssuanceRound = ''
      this.queryParams.fundId = val
      // findIssuanceRoundListByFundId(this.queryParams).then(result => {
      //   this.fundIssuanceRoundList = result.data
      // })
      if (this.operateData.clickDataSave.type === 'call') {
        this.getLpBaseList(val)
      }
    },
    getLpBaseList(val) {
      this.queryParams.fundId = val
      this.queryParams.callPeriod = this.operateData.layerOperateForm.fundIssuanceRound
      // findLpListByFundId(this.queryParams).then(result => {
      //   this.lpList = result.data
      // })
    },
    lpListChange(val) {
      this.operateData.layerOperateForm.lps = ''
      this.getLpBaseList(val)
    },
    /**
     * 查询在管基金
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/14 10:19
     */
    searchFundInfoList() {
      findFund({}).then(result => {
        this.selectData.fundList = result.data
      })
    },

    /**
     * 点击生成报告
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/14 10:14
     */
    clickGeneration(rowData) {
      this.operateData.showLayer = true
      this.operateData.layerTitle = '生成 - ' + rowData.fileNameSuffix
      Object.assign(this.operateData.clickDataSave, rowData)
      this.operateType = rowData.type
      // 查询基金
      this.searchFundInfoList()
      // 查询lp
      this.getLpBaseList()
    },
    /**
     * 关闭生成弹窗
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/14 10:21
     */
    rightTopBtnClose(done) {
      this.operateData.showLayer = false
      if (done !== undefined) {
        done()
      }
    },
    /**
     * 生成弹窗销毁后 重置数据
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/14 10:23
     */
    closed(callback) {
      Object.assign(this.$data.operateData.layerOperateForm, this.$options.data().operateData.layerOperateForm)
      Object.assign(this.$data.operateData.layerTitle, this.$options.data().operateData.layerTitle)
      Object.assign(this.$data.operateData.clickDataSave, this.$options.data().operateData.clickDataSave)

      if (callback !== undefined) {
        callback()
      }
    },
    /**
     * 生成弹窗点击确认
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/14 10:24
     */
    clickLayerOperateSubmit() {
      const data = this.operateData.clickDataSave
      // const type = data.type
      this.exportFile(data)
      /* if(type.indexOf("onePage") !== -1){
        this.exportFile(data)
      }*/
    },
    isBlank(data) {
      return data === undefined || data === null || data === ''
    },
    /**
     * 导出文件
     * @author YangMiao 1939724848@qq.com
     * @date   2022/4/2 14:40
     */
    exportFile(rowData) {
      this.loading = true
      const params = Object.assign({}, this.operateData.layerOperateForm)
      const type = this.operateData.clickDataSave.type
      if (type === 'onePage' || type === 'xmzb' || type === 'jdthmb' || type === 'ndthmb') {
        if (this.isBlank(params.dealId)) {
          this.$message.error('请选择项目')
          return
        }
      }
      if (type === ('onePage')) {
        if (this.isBlank(params.updateTime)) {
          this.$message.error('请选择更新时间')
          return
        }
      }
      if (type === ('jjyybg')) {
        if (this.isBlank(params.fundId)) {
          this.$message.error('请选择基金')
          return
        }
        if (this.isBlank(params.reportType)) {
          this.$message.error('请选择报告类型')
          return
        }
        if (this.isBlank(params.year)) {
          this.$message.error('请选择年度')
          return
        }
        if (this.isBlank(params.quarter) && params.reportType === 'jb') {
          this.$message.error('请选择季度')
          return
        }
      }
      if (type === 'jdthmb') {
        if (this.isBlank(params.year)) {
          this.$message.error('请选择年份')
          return
        }
        if (this.isBlank(params.quarter)) {
          this.$message.error('请选择季度')
          return
        }
        params.type = '2'
      }
      if (type === 'ndthmb') {
        if (this.isBlank(params.year)) {
          this.$message.error('请选择年份')
          return
        }
        params.type = '1'
      }
      console.log('准备下载')
      // 准备下载
      axios({
        method: 'post',
        url: process.env.VUE_APP_BASE_API + rowData.url,
        data: params,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(res => {
        const blob = res.data
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          // 获取选择的基金名称
          const fileName = rowData.fileName
          a.download = fileName + `.docx`
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        this.loading = false
      })
      this.rightTopBtnClose()
    },

    /**
     * 导出call款
     * @author YangMiao 1939724848@qq.com
     * @date   2021/12/15 11:09
     */
    exportFundCall(rowData) {
      this.loading = true
      const params = Object.assign({}, this.operateData.layerOperateForm)
      // 校验基金名称跟lp 这两个是必填的
      if (params.fundId === null || params.fundId === undefined || params.fundId === '') {
        this.$message.error('请选择基金')
        return
      } else if (params.lps === null || params.lps === undefined || params.lps.length === 0) {
        this.$message.error('请选择LP')
        return
      }
      params.lwIdList = params.lps
      // 准备下载
      axios({
        method: 'post',
        url: process.env.VUE_APP_BASE_API + rowData.url,
        data: params,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(res => {
        const blob = res.data
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = `资产证明Call款.zip`
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        this.loading = false
      })
      this.rightTopBtnClose()
    }
  }
}
</script>

<style scoped>

</style>
